﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tensop.Net
{
    public class ProtocolManager
    {
        IProtocolHeaderParser                               HeaderParser;
        Dictionary<string,IProtocolDataParser>              namedMapping;

        public ProtocolManager(IProtocolHeaderParser headerParser)
        {
            HeaderParser = headerParser ?? throw new NullReferenceException();
            namedMapping = new Dictionary<string, IProtocolDataParser>( 8 );
        }

        public byte[] Parse(byte[] data, Core.ConnectionContext cc)
        {
            var protocolName = HeaderParser.MappingProtocol( data );
            var parser = namedMapping[protocolName];
            var result = parser.Proc( data, cc );
            var feedBack = parser.FeedBack( result );
            return feedBack;
        }

        public string this[IProtocolDataParser parser] {
            get {
                var protocolName = parser.GetType().Name;
                try
                {
                    namedMapping.Add( protocolName, parser );
                }
                catch { }
                return protocolName;
            }
        }

        public void Remove(string name)
        {
            try
            {
                lock ( namedMapping )
                    namedMapping.Remove( name );
            }
            catch { }
        }
    }
}
